package services

import (
	"errors"
	"gin-study/app/dao"
	"gin-study/app/event"
	"gin-study/app/event/events"
	"gin-study/app/http/requests"
	"gin-study/app/models"
	"github.com/spf13/cast"
)

var Auth *auth

func init() {
	Auth = new(auth)
}

type auth struct {
}

func (this *auth) Register(params *requests.RegisterReq) (user *models.User, err error) {
	user = &models.User{
		Nickname: params.Nickname,
		Username: params.Username,
		Password: params.Password,
	}
	err = dao.User.Save(user).Error

	event.New(&events.Register{User: user})

	return
}

func (this *auth) Login(params *requests.LoginReq) (user *models.User, err error) {
	err = dao.User.Where("username", params.Username).First(&user).Error
	if err != nil {
		return
	}
	if user.Password != params.Password {
		return nil, errors.New("密码错误")
	}
	return
}

func (this *auth) GetToken(user *models.User) string {
	return "token" + cast.ToString(user.Username)
}
